package com.wfu.module_local_video.business;

import android.annotation.SuppressLint;
import android.content.Context;

import com.wfu.module_local_video.bean.MediaItem;
import com.wfu.module_local_video.business.base.IBaseBusiness;
import com.wfu.module_local_video.dao.LVideoDao;
import com.wfu.module_local_video.view.base.IBaseView;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

public class LVideoBusiness implements IBaseBusiness<IBaseView> {
    private final LVideoDao model;
    private IBaseView mView;

    public LVideoBusiness(IBaseView view) {
        model = new LVideoDao();
        this.mView = view;
    }

    @SuppressLint("CheckResult")
    public void getLocalVideoFromSD(Context context) {
        mView.setLoadingVisiblity(true);
        model.getData(context)
                .map(cursor -> {
                    List<MediaItem> mediaItems = new ArrayList<>();
                    while (cursor != null && cursor.moveToNext()) {
                        MediaItem mediaItem = new MediaItem();
                        mediaItem.name = cursor.getString(0);//视频的名称
                        mediaItem.duration = cursor.getLong(1);//视频的时长
                        mediaItem.size = cursor.getLong(2);//视频的文件大小
                        mediaItem.data = cursor.getString(3);//视频的播放地址
                        mediaItem.artist = cursor.getString(4);//艺术家
                        mediaItems.add(mediaItem);
                    }
                    return mediaItems;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> mView.setLoadingVisiblity(false))
                .subscribe(mediaItems -> {
                            mView.onSuccess(mediaItems);
                        },
                        throwable -> {
                            throwable.printStackTrace();
                            mView.onFailed(throwable);
                        });
    }
}
